/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.beer;

import beans.Beer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.xmlrules.FromXmlRulesModule;
import org.xml.sax.SAXException;
import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;

/**
 *
 * @author heinen
 */
public class BeerReader {

    private List<Beer> beers;

    public BeerReader() {
        beers = new ArrayList<>();
    }

    public void addBeer(Beer beer) {
        beers.add(beer);
    }

    public List<Beer> getAllBeers() {

        final String rulesfileName = "src/xml/beer/BeerRules.xml";
        String datafileName = "src/xml/beer/beers.xml";
        File f = new File(datafileName);
        if (!f.exists()) {
            return null;
        }
        Digester d = newLoader(new FromXmlRulesModule() {
            @Override
            protected void loadRules() {
                loadXMLRules(new File(rulesfileName));
            }
        }).newDigester();

        //Beers beers = new Beers();
        d.push(this);

        try {
            File srcFile = new File(datafileName);
            d.parse(srcFile);
        } catch (IOException ioe) {
            System.out.println("Error reading input file:" + ioe.getMessage());
            System.exit(-1);
        } catch (SAXException se) {
            System.out.println("Error parsing input file:" + se.getMessage());
            System.exit(-1);
        }

        return beers;
    }

    public Beer getBeerByName(String name) {
        List<Beer> allBeers = getAllBeers();
        for (Beer b : beers) {
            if (b.getName().equalsIgnoreCase(name)) {
                return b;
            }
        }
        return null;
    }

    public Beer getBeerById(Long id) {
        List<Beer> allBeers = getAllBeers();
        for (Beer b : beers) {
            if (b.getId().equals(id)) {
                return b;
            }
        }
        return null;
    }
}
